import wx
import wx.aui
import wx.lib.docview
import mumodel

#============================================================================

class MuApp(wx.App):
	def OnInit(self):
		print 'OnInit'
#		splash = wx.SplashScreen(splash_bmp, wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_NO_TIMEOUT, 0, None, -1, style=wx.SIMPLE_BORDER|wx.FRAME_NO_TASKBAR)
#		splash.Show()
		self.SetAppName('Mushclient Plugin Editor')
		docmgr = wx.lib.docview.DocManager(flags = wx.lib.docview.DOC_MDI)
		doctmpl = wx.lib.docview.DocTemplate(docmgr, 'Plugin',
									 '*.mcp;*.xml',
									 None, '.mcp',
									 'Muclient Document',
									 'Muclient View',
									 MuDocument,
									 MuView)
		frame = wx.lib.docview.DocMDIParentFrame(docmgr, None, -1, 'Muclient Test')
		menu = wx.Menu()
		menu.Append(wx.ID_NEW, '&New')
		menu.Append(wx.ID_OPEN, '&Open')
		menu.Append(wx.ID_CLOSE, '&Close')
		menu.Append(wx.ID_SAVE, '&Save')
		menu.Append(wx.ID_SAVEAS, 'Save &As')
		menu.Append(wx.ID_EXIT, 'E&xit')
		docmgr.FileHistoryUseMenu(menu)
		menubar = wx.MenuBar()
		menubar.Append(menu, '&File')
		frame.SetMenuBar(menubar)
		frame.Show(True)
		self.SetTopWindow(frame)
		return True

class MuDocument(wx.lib.docview.Document):

	def __init__(self):
		wx.lib.docview.Document.__init__(self)
		self.doc = mumodel.Document()

	def OnCreate(self, path, flags):
		print 'OnCreateDocument', path, flags
		return wx.lib.docview.Document.OnCreate(self, path, flags)
#        if flags & DOC_NO_VIEW:
#            return True
#        return self.GetDocumentTemplate().CreateView(self, flags)

	def OnOpenDocument(self, filename):
		print 'OnOpenDocument', filename
		if not self.OnSaveModified():
			return False
		try:
			self.doc.load(filename)
		except IOError as err:
			pass # XXX do something
			print 'boo!', err
			return False
		self.SetDocumentModificationDate()
		self.SetFilename(filename, True)
		self.Modify(False)
		self.SetDocumentSaved(True)
		self.UpdateAllViews(hint=('load', self, filename))
		return True

	def OnSaveDocument(self, filename):
		print 'OnSaveDocument', filename
		if not filename:
			return False
		try:
			if os.path.exists(filename):
				bakfile = os.path.splitext(filename)[0] + '.bak'
				if os.name == 'nt' and os.path.exists(bakfile):
					os.remove(bakfile)
				os.rename(filename, bakfile)
			self.doc.save(filename)
		except IOError as err:
			pass # XXX do something. errno 13 is access denied
			print 'boo!', err
			return False
		self.SetDocumentModificationDate()
		self.SetFilename(filename, True)
		self.Modify(False)
		self.SetDocumentSaved(True)
		return True

#	def IsModified(self):
#		view = self.GetFirstView()
#		if view and view.GetTextCtrl():
#			return view.GetTextCtrl().IsModified()
#		return False

#	def Modify(self, modify):
#		if self._inModify:
#			return
#		self._inModify = True
#		
#		view = self.GetFirstView()
#		if not modify and view and view.GetTextCtrl():
#			view.GetTextCtrl().DiscardEdits()
#
#		wx.lib.docview.Document.Modify(self, modify)  # this must called be after the DiscardEdits call above.
#
#		self._inModify = False

class MuView(wx.lib.docview.View):
#	OnCreate, OnDraw, OnUpdate and OnClose
	def OnCreate(self, doc, flags):
		print 'OnCreate', doc, flags
		frame = wx.lib.docview.DocMDIChildFrame(doc, self, 
						wx.GetApp().GetTopWindow(), -1, 
						wx.GetApp().GetAppName(), (10, 10), (300, 300), 
						wx.DEFAULT_FRAME_STYLE)
		self.textctrl = wx.TextCtrl(frame, style=wx.TE_MULTILINE)
		sizer = wx.BoxSizer()
		sizer.Add(self.textctrl, 1, wx.EXPAND|wx.ALL, 8)
		frame.Sizer = sizer
		self.SetFrame(frame)
		self.textctrl.AppendText('OnCreate: %s %s\n' % (doc, flags))
		return True

	def OnUpdate(self, sender, hint):
		print 'OnUpdate', sender, hint
		self.textctrl.AppendText('OnUpdate: %s %s\n' % (sender, hint))
		if not hint:
			print 'missing Update hint'
		elif hint[0] == 'load':
			self.DoLoad()
		elif hint[0] == 'modify':
			self.GetFrame().OnTitleIsModified()
		else:
			print 'unknown Update hint'

	def DoLoad(self):
		doc = self.GetDocument().doc


##CHK_3STATE_STYLE = wx.CHK_3STATE | wx.CHK_ALLOW_3RD_STATE_FOR_USER
##EN_WIDTH = 7

##def MuChoiceBox(parent, choices):
##	ctrl = wx.Choice(parent, choices=[item[1] for item in choices])
##	ctrl.MinSize = ctrl.Size - (EN_WIDTH, 0)
##	return ctrl


#class XmlValidator(wx.PyValidator):
###	def __init__(self, attr):
###		wx.PyValidator.__init__(self)
###		self.attr = attr
#	def Clone(self):
#		kwargs = dict((k,v) for k,v in vars(self).items() if k.islower() and not k == 'this')
##		foo = vars(self)
##		foo = self.__dict__.copy()
#		print 'boo!', kwargs
##		return self
##		del foo['this']
#		return type(self)(**kwargs)
#	def TransferToWindow(self):
#		self.Load(self.Window, self.Window.Parent.xmlelem)
#	def TransferFromWindow(self):
#		self.Save(self.Window, self.Window.Parent.xmlelem)

#class XmlGenAttr(XmlValidator):
#	def __init__(self, attr):
#		XmlValidator.__init__(self)
#		self.attr = attr
##	def InitControl(self, ctrl):
##		self.kind = type(ctrl.Value)
#	def Load(self, ctrl, elem):
#		ctrl.Value = getxmlval(elem, self.attr, self.kind)
#	def Save(self, ctrl, elem):
#		setxmlval(elem, self.attr, ctrl.Value)

#class Xml3stateAttr(XmlValidator):
#	def __init__(self, flagattr, valattr):
#		XmlValidator.__init__(self)
#		self.flagattr = flagattr
#		self.valattr = valattr
##	def InitControl(self, ctrl):
##		print "InitControl", ctrl, ctrl.WindowStyle, self.flagattr, self.valattr
##		ctrl.WindowStyle = (wx.CHK_3STATE | wx.CHK_ALLOW_3RD_STATE_FOR_USER)
##		print " and now", ctrl.WindowStyle
#	def Load(self, ctrl, elem):
#		if getxmlval(elem, self.flagattr, bool):
#			ctrl.ThreeStateValue = getxmlval(elem, self.valattr, bool)
#		else:
#			ctrl.ThreeStateValue = wx.CHK_UNDETERMINED
#	def Save(self, ctrl, elem):
#		setxmlval(elem, self.flagattr, self.ThreeStateValue != wx.CHK_UNDETERMINED)
#		setxmlval(elem, self.valattr, self.ThreeStateValue == wx.CHK_CHECKED)

#class XmlListAttr(XmlValidator):
#	def __init__(self, attr, choices):
#		XmlValidator.__init__(self)
#		self.attr = attr
#		self.choices = choices
##	def InitControl(self, ctrl):
##		print "InitControl", ctrl, self.attr, self.choices
##		self.selmap = dict((item[0], idx) for idx, item in enumerate(self.choices))
##		ctrl.Items = [item[1] for item in self.choices]
##		ctrl.Refresh()
##		print ctrl.Items
##		ctrl.MinSize = ctrl.Size - (ctrl.CharWidth, 0)
#	def Load(self, ctrl, elem):
#		if type(self.attr) is str:
#			value = getxmlval(elem, self.attr, int)
#		else:
#			flagattr, valattr = self.attr
#			value = getxmlval(elem, flagattr, bool) and getxmlval(elem, valattr, int)
#		self.Selection = self.selmap.get(value, wx.NOT_FOUND)
#	def Save(self, ctrl, elem):
#		value = self.choices[self.Selection][0]
#		if type(self.attr) is str:
#			setxmlval(elem, self.attr, value)
#		else:
#			flagattr, valattr = self.attr
#			setxmlval(elem, flagattr, value != 0)
#			setxmlval(elem, valattr, value)

#class MuPanelBase(wx.Panel):
#	def __init__(self, parent, modelitem):
#		wx.Panel.__init__(self, parent)

#class MuCtrlPanel(MuPanelBase):
#	def Load(self):

#class XmlCtrlPanel(wx.PyPanel):

#	def __init__(self, *args, **kwargs):
#		wx.PyPanel.__init__(self, *args, **kwargs)
#		self.Sizer = wx.BoxSizer(wx.VERTICAL)
###		self._ctrlset = set()
###		self._attrmap = {None: etree.Element}
###		for cls in type(self).__mro__:
####			if hasattr(cls, '_attrs_'):
####				self._attrmap.update(cls.attrs)
###			for item in getattr(cls, '_attrs_', ()):
###				if type(item) is list:
###					pass
###				else:
###					name, kind = item
###					self._attrmap_[name] = kind
###					self.ctrlmap[name]
###			if cls is MuPanelBase:
###				break

#	def AddChild(self, child):
#		wx.PyPanel.AddChild(self, child)
#		print "AddChild", child, child.Validator
#		if isinstance(child.Validator, XmlValidator):
#			child.Validator.InitControl(child)

#	def AddBox(self, label, stretch=False, border=8):
#		sizer = wx.StaticBoxSizer(wx.StaticBox(self, label=label), wx.VERTICAL)
#		self.Sizer.Add(sizer, stretch, wx.EXPAND | wx.ALL, border)

#	def AddRow(self, stretch=False, border=6):
#		self._cursizer = wx.BoxSizer(wx.HORIZONTAL)
#		count = self.Sizer.GetItemCount()
#		container = self.Sizer.GetItem(count - 1).Sizer if count else self.Sizer
#		container.Add(self._cursizer, stretch, wx.EXPAND | wx.ALL, border)

#	def AddItem(self, ctrl, space=None, slide=False, stretch=0, flags=wx.ALIGN_CENTER_VERTICAL):
#		sizer = self._cursizer
#		count = sizer.GetItemCount()
#		horiz = sizer.Orientation == wx.HORIZONTAL
#		if space or slide or (space is None and count and not
#				(horiz and isinstance(sizer.GetItem(count-1).Window, wx.StaticText))):
#			if space is None:
#				space = 8 if horiz else 6
#			if horiz:
#				sizer.Add((space, 1), slide)
#			else:
#				sizer.Add((1, space), slide)
##		if slide or (hspace and vspace and count and (sizer.Orientation == wx.VERTICAL
##					 or not isinstance(sizer.GetItem(count-1).Window, wx.StaticText))):
##		if slide or (hspace and vspace and (sizer.Orientation == wx.VERTICAL or count
##					 and not isinstance(sizer.GetItem(count-1).Window, wx.StaticText))):
##			sizer.Add((hspace, vspace), slide)
#		if isinstance(ctrl, basestring):
#			ctrl = wx.StaticText(self, label=ctrl)
#		elif isinstance(ctrl, wx.Sizer):
#			self._cursizer = ctrl
#		if ctrl is not None:
#			sizer.Add(ctrl, stretch, flags)

##	def AddLabel(self, label, *args, **kwargs):
##		self.AddItem(wx.StaticText(self, label=label), *args, **kwargs)

##	def AddSizer(self, sizer, *args, **kwargs):
##		self.AddItem(sizer, *args, **kwargs)
##		self.cur_row = sizer

##	def AddItemV(self, ctrl):
##		sizer = self.cur_row
##		if sizer.Children:
##			sizer.AddSpacer(6)
##		sizer.Add(ctrl)

##	def CreateCtrl(self, cls, attr, *args, **kwargs):
##		if issubclass(cls, (wx.TextCtrl, wx.ComboBox)):
##			assert type(attr) is str
##			def Load(self, elem):
##				self.Value = getxmlval(elem, self._attr, str)
##			def Save(self, elem):
##				setxmlval(elem, self._attr, self.Value)
##		elif issubclass(cls, wx.SpinCtrl):
##			assert type(attr) is str
##			def Load(self, elem):
##				self.Value = getxmlval(elem, self._attr, int)
##			def Save(self, elem):
##				setxmlval(elem, self._attr, self.Value)
####		elif issubclass(cls, wx.SpinCtrlDouble):
####			assert type(attr) is str
####			def Load(self, elem):
####				self.Value = getxmlfloat(elem, self._attr)
####			def Save(self, elem):
####				setxmlfloat(elem, self._attr, self.Value)
##		elif issubclass(cls, wx.CheckBox):
##			if type(attr) is str:
##				def Load(self, elem):
##					self.Value = getxmlval(elem, self._attr, bool)
##				def Save(self, elem):
##					setxmlval(elem, self._attr, self.Value)
##			else:
##				def Load(self, elem):
##					flagattr, valattr = self._attr
##					self.ThreeStateValue = getxmlval(elem, valattr, bool) if getxmlval(elem, flagattr, bool) else wx.CHK_UNDETERMINED
##				def Save(self, elem):
##					flagattr, valattr = self._attr
##					setxmlval(elem, flagattr, self.ThreeStateValue != wx.CHK_UNDETERMINED)
##					setxmlval(elem, valattr, self.ThreeStateValue == wx.CHK_CHECKED)
##				kwargs['style'] = wx.CHK_3STATE | wx.CHK_ALLOW_3RD_STATE_FOR_USER
##		elif issubclass(cls, wx.Choice):
##			if type(attr) is str:
##				def Load(self, elem):
##					value = getxmlval(elem, self._attr, int)
##					self.Selection = self._selmap.get(value, wx.NOT_FOUND)
##				def Save(self, elem):
##					value = self._sellst[self.Selection][0]
##					setxmlval(elem, self._attr, value)
##			else:
##				def Load(self, elem):
##					flagattr, valattr = self._attr
##					value = getxmlval(elem, flagattr, bool) and getxmlval(elem, valattr, int)
##					self.Selection = self._selmap.get(value, wx.NOT_FOUND)
##				def Save(self, elem):
##					flagattr, valattr = self._attr
##					value = self._sellst[self.Selection][0]
##					setxmlval(elem, flagattr, value != 0)
##					setxmlval(elem, valattr, value)
##			sellst = kwargs['choices']
##			selmap = dict((item[0], idx) for idx, item in enumerate(sellst))
##			kwargs['choices'] = [item[1] for item in sellst]
##		else:
##			raise ValueError('invalid control class %r' % cls.__name__)
##
##		ctrl = cls(self, *args, **kwargs)
##		ctrl.Load = Load
##		ctrl.Save = Save
##		ctrl._attr = attr
##		if issubclass(cls, wx.Choice):
##			ctrl._sellst = sellst
##			ctrl._selmap = selmap
##			ctrl.MinSize = ctrl.Size - (ctrl.CharWidth, 0)
##		self._ctrlset.add(ctrl)

##	def Load(self, elem):
##		for ctrl in self._ctrlset:
##			ctrl.Load(elem)
##
##	def Save(self, elem):
##		for ctrl in self._ctrlset:
##			ctrl.Save(elem)
		##
##		for name, attr in self._ctrlmap.iteritems():
##			ctrl = getattr(self, name, None)
##			if ctrl is None:
##				continue
##			if type(attr) is str:
##				kind = self._attrmap[attr]
##				value = getxmlval(elem, attr, kind)
##				if isinstance(ctrl, wx.Choice):
##					ctrl.Selection = foo.get(value, wx.NOT_FOUND)
##				else:
##					ctrl.Value = value
##			else:
##				flagattr, ctrlattr = attr
##				flagval = getxmlval(elem, flagattr, self._attrmap[flagattr])
##				ctrlval = getxmlval(elem, ctrlattr, self._attrmap[ctrlattr])
##				if isinstance(ctrl, wx.Choice):
##					ctrl.Selection = flagval and ctrlval
##				elif isinstance(ctrl, wx.CheckBox):
##					ctrl.ThreeStateValue = ctrlval if flagval else wx.CHK_UNDETERMINED
##				else:
##					raise RuntimeError('invalid control type %r' % type(ctrl))

##	def getxmlval(self, name=None):
##		try:
##			kind = self._attrmap[name]
##		except KeyError:
##			raise ValueError('%r object has no attribute %r' % (type(self).__name__, name))
##		if kind is bool:
##			return self.elem.get(name) == 'y'
##		elif kind is int:
##			return int(self.elem.get(name, 0))
##		elif kind is str:
##			return self.elem.get(name, '')
##		elif kind is etree.Element:
##			return self.elem.text
##		elif kind is etree.SubElement:
##			return self.elem.findtext(name, '')
##		elif type(kind) is list:
##			map = dict((itm[0], idx) for idx, itm in enumerate(kind))
##			return map.get(int(self.elem.get(name, 0)), wx.NOT_FOUND)
##		else:
##			raise RuntimeError('%r object has unknown attribute type %r' % (type(self).__name__, kind))
##
##	def get3wayval(self, flag, name):
##		if not self.getxmlval(flag):
##			return wx.CHK_UNDETERMINED
##		elif self.getxmlval(name):
##			return wx.CHK_CHECKED
##		else:
##			return wx.CHK_UNCHECKED
##
##	def setxmlval(self, name, value=None):
##		if value is None:
##			name, value = value, name
##		try:
##			kind = self._attrmap[name]
##		except KeyError:
##			raise ValueError('%r object has no attribute %r' % (type(self).__name__, name))
##		if not value:  # this relies on map types always having 0-valued first element
##			if kind is etree.Element:
##				self.elem.text = None
##			elif kind is etree.SubElement:
##				etree.strip_elements(self.elem, name)
##			else:
##				self.elem.attrib.pop(name, None)
##		elif kind is bool:
##			self.elem.set(name, 'y')
##		elif kind is int:
##			self.elem.set(name, str(value))
##		elif kind is str:
##			self.elem.set(name, value)
##		elif kind is etree.Element:
##			if self.elem.tag is not etree.Comment and '\n' in value:
##				value = etree.CDATA(value)
##			self.elem.text = value
##		elif kind is etree.SubElement:
##			subelem = self.elem.find(name)
##			if subelem is None:
##				subelem = etree.SubElement(elem, name)
##			subelem.text = value
##		elif type(kind) is list:
##			self.elem.set(name, str(kind[value][0]))
##		else:
##			raise RuntimeError('%r object has unknown attribute type %r' % (type(self).__name__, kind))
##
##	def set3wayval(self, flag, name, value):
##		self.setxmlval(flag, value != wx.CHK_UNDETERMINED)
##		self.setxmlval(name, value == wx.CHK_CHECKED)

#class MuPluginPanel(XmlCtrlPanel):
#	pass

#class MuListPanel(XmlCtrlPanel):
#	pass

#class MuAliasesGroupPanel(MuListPanel):
#	pass

#class MuTriggersGroupPanel(MuListPanel):
#	pass

#class MuTimersGroupPanel(MuListPanel):
#	pass

#class MuVariablesPanel(MuListPanel):
#	pass

#class MuDetailPanel(XmlCtrlPanel):

##	attrs = dict(name=str, group=str, enabled=bool, match=str, sequence=int,
##				 regexp=bool, ignore_case=bool, keep_evaluating=bool,
##				 send_to=SENDTO_CHOICES, script=str, variable=str,
##				 send=etree.SubElement, one_shot=bool, omit_from_log=bool, 
##				 omit_from_output=bool)
##
##	def Load(self, elem):
###		MuPanelBase.Load(self, elem)
##		self.elem = elem
###
##		self.name.Value = self.getxmlval('name')
##		self.group.Value = self.getxmlval('group')
##		self.enabled.Value = self.getxmlval('enabled')
##		if hasattr(self, 'match_text'):
##			self.match_text.Value = self.getxmlval('match')
##			self.sequence.Value = self.getxmlval('sequence')
##			self.regexp.Value = self.getxmlval('regexp')
##			self.ignore_case.Value = self.getxmlval('ignore_case')
##			self.keep_eval.Value = self.getxmlval('keep_evaluating')
##		self.send_to.Selection = self.getxmlval('send_to')
##		self.script.Value = self.getxmlval('script')
##		self.variable.Value = self.getxmlval('variable')
##		self.send_text.Value = self.getxmlval('send')
##		self.one_shot.Value = self.getxmlval('one_shot')
##		self.omit_log.Value = self.getxmlval('omit_from_log')
##		self.omit_out.Value = self.getxmlval('omit_from_output')
##
##	def Save(self):
###		MuPanelBase.Save(self)
##		self.setxmlval('name', self.name.Value)
##		self.setxmlval('group', self.group.Value)
##		self.setxmlval('enabled', self.enabled.Value)
##		if hasattr(self, 'match_text'):
##			self.setxmlval('match', self.match_text.Value)
##			self.setxmlval('sequence', self.sequence.Value)
##			self.setxmlval('regexp', self.regexp.Value)
##			self.setxmlval('ignore_case', self.ignore_case.Value)
##			self.setxmlval('keep_evaluating', self.keep_eval.Value)
##		self.setxmlval('send_to', self.send_to.Selection)
##		self.setxmlval('script', self.script.Value)
##		self.setxmlval('variable', self.variable.Value)
##		self.setxmlval('send', self.send_text.Value)
##		self.setxmlval('one_shot', self.one_shot.Value)
##		self.setxmlval('omit_from_log', self.omit_log.Value)
##		self.setxmlval('omit_from_output', self.omit_out.Value)

#	def CreateGeneral(self):
#		self.AddRow(border=8)
##		hsizer = wx.BoxSizer(wx.HORIZONTAL)
##		self.Sizer.Add(hsizer, 0, wx.ALL | wx.EXPAND, 8)
#		self.AddItem('Name:  ', space=12)
##		hsizer.AddSpacer(12)
##		hsizer.Add(wx.StaticText(self, label='Name:  '), 0, wx.ALIGN_CENTER)
#		self.name = wx.TextCtrl(self, validator=XmlGenAttr('name'))
##		self.name = self.CreateCtrl(wx.TextCtrl, 'name')
##		self.name = wx.TextCtrl(self)
#		self.AddItem(self.name, stretch=5)
##		hsizer.Add(self.name, 5)
#		self.AddItem('Group:  ', slide=True)
##		hsizer.AddStretchSpacer()
##		hsizer.Add(wx.StaticText(self, label='Group:  '), 0, wx.ALIGN_CENTER)
#		self.group = wx.TextCtrl(self, validator=XmlGenAttr('group'))
##		self.group = self.CreateCtrl(wx.TextCtrl, 'group')
##		self.group = wx.TextCtrl(self)
#		self.AddItem(self.group, stretch=5)
##		hsizer.Add(self.group, 5)
##		hsizer.AddStretchSpacer()
#		self.enabled = wx.CheckBox(self, validator=XmlGenAttr('enabled'), label='Enabled')
##		self.enabled = self.CreateCtrl(wx.CheckBox, 'enabled', label='Enabled')
##		self.enabled = wx.CheckBox(self, label='Enabled')
#		self.enabled.Value = True
#		self.AddItem(self.enabled, slide=True)
##		hsizer.Add(self.enabled, 0, wx.ALIGN_CENTER)
#		self.AddItem(None, space=8)
##		hsizer.AddSpacer(8)

#	def CreateInput(self):
#		self.AddBox('Input')
###		self.cur_box = wx.StaticBoxSizer(wx.StaticBox(self, label='Input'), wx.VERTICAL)
###		self.Sizer.Add(self.cur_box, 0, wx.ALL | wx.EXPAND, 8)
#		# match row
#		self.AddRow()
##		hsizer = wx.BoxSizer(wx.HORIZONTAL)
##		self.cur_box.Add(hsizer, 0, wx.EXPAND | wx.ALL, 8)
#		self.AddItem('Match:  ')
##		hsizer.Add(wx.StaticText(self, label='Match:  '), 0, wx.ALIGN_CENTER)
#		self.match_text = wx.TextCtrl(self, validator=XmlGenAttr('match'))
##		self.match_text = self.CreateCtrl(wx.TextCtrl, 'match')
##		self.match_text = wx.TextCtrl(self)
#		self.AddItem(self.match_text, stretch=20)
##		hsizer.Add(self.match_text, 20)
##		hsizer.Add((10, 1), 1)
##		hsizer.AddSpacer(10)
##		hsizer.AddStretchSpacer()
#		self.AddItem('Sequence:  ', slide=True)
##		hsizer.Add(wx.StaticText(self, label='Sequence:  '), 0, wx.ALIGN_CENTER)
#		self.sequence = wx.SpinCtrl(self, # validator=XmlGenAttr('sequence'),
#									size=(54,-1), min=1, max=9999, initial=100)
#		self.sequence.Validator = XmlGenAttr('sequence')
##		self.sequence = self.CreateCtrl(wx.SpinCtrl, 'sequence', size=(54,-1), min=1, max=9999, initial=100)
##		self.sequence = wx.SpinCtrl(self, size=(54,-1), min=1, max=9999, initial=100)
#		self.AddItem(self.sequence)
##		hsizer.Add(self.sequence)
#		# flags row
#		self.AddRow()
#		self.AddItem('Flags:    ')
#		self.AddItem(wx.WrapSizer(wx.HORIZONTAL, 2), stretch=True, flags=wx.EXPAND)
#		self.regexp = wx.CheckBox(self, validator=XmlGenAttr('regexp'), label='regular expr')
#		self.AddItem(self.regexp)
#		self.ignore_case = wx.CheckBox(self, validator=XmlGenAttr('ignore_case'), label='ignore case')
#		self.AddItem(self.ignore_case)
#		self.keep_eval = wx.CheckBox(self, validator=XmlGenAttr('keep_evaluating'), label='keep evaluating')
#		self.AddItem(self.keep_eval)

#	def CreateOutput(self):
#		self.AddBox('Input')
###		self.cur_box = wx.StaticBoxSizer(wx.StaticBox(self, label='Output'), wx.VERTICAL)
###		self.Sizer.Add(self.cur_box, 1, wx.ALL | wx.EXPAND, 8)
#		# send to row
#		self.AddRow()
##		hsizer = wx.BoxSizer(wx.HORIZONTAL)
##		self.cur_box.Add(hsizer, 0, wx.EXPAND | wx.ALL, 8)
#		self.AddItem('Send to:   ')
##		hsizer.Add(wx.StaticText(self, label='Send to:  '), 0, wx.ALIGN_CENTER)
#		self.send_to = wx.Choice(self, validator=XmlListAttr('send_to', SENDTO_CHOICES))
##		self.send_to = wx.Choice(self, choices=[x[1] for x in SENDTO_CHOICES])
##		self.send_to.MinSize = self.send_to.Size - (EN_WIDTH, 0)
#		self.AddItem(self.send_to)
##		hsizer.Add(self.send_to, 0)
##		hsizer.Add((10, 1), 1)
##		hsizer.AddSpacer(10)
##		hsizer.AddStretchSpacer()
#		self.AddItem('Call script:  ', space=16, slide=True)
##		hsizer.Add(wx.StaticText(self, label='Call script:  '), 0, wx.ALIGN_CENTER)
#		self.script = wx.ComboBox(self, validator=XmlGenAttr('script')) #, size=(EN_WIDTH*12,-1), style=wx.CB_DROPDOWN|wx.CB_SORT)
#		self.script.MinSize = (self.script.CharWidth*12, -1)
#		self.AddItem(self.script, stretch=5)
##		hsizer.Add(self.script, 5)
#		self.AddItem('Set variable:  ', space=16, slide=True)
##		hsizer.AddSpacer(10)
##		hsizer.AddStretchSpacer()
##		hsizer.Add(wx.StaticText(self, label='Set variable:  '), 0, wx.ALIGN_CENTER)
#		self.variable = wx.ComboBox(self, validator=XmlGenAttr('variable')) #, size=(EN_WIDTH*12,-1), style=wx.CB_DROPDOWN|wx.CB_SORT)
#		self.AddItem(self.variable, stretch=5)
##		hsizer.Add(self.variable, 5)
#		# send text and flags row
#		self.AddRow(stretch=True)
##		hsizer = wx.BoxSizer(wx.HORIZONTAL)
##		self.cur_box.Add(hsizer, 1, wx.EXPAND | wx.ALL, 8)
#		self.send_text = wx.TextCtrl(self, validator=XmlGenAttr('./send'), style=wx.TE_MULTILINE)
#		self.AddItem(self.send_text, stretch=1, flags=wx.EXPAND)
##		hsizer.Add(self.send_text, 1, wx.EXPAND)
#		###
#		self.AddItem(wx.BoxSizer(wx.VERTICAL), space=12, flags=0)
##		hsizer.AddSpacer(15)
##		self.cur_row = wx.BoxSizer(wx.VERTICAL)
##		hsizer.Add(self.cur_row)
#		self.AddItem('Flags:')
##		self.AddItem(wx.StaticText(self, label='Flags:'))
#		self.one_shot = wx.CheckBox(self, validator=XmlGenAttr('one_shot'), label='one-shot')
#		self.AddItem(self.one_shot) #, vspace=10)
#		self.omit_log = wx.CheckBox(self, validator=XmlGenAttr('omit_from_log'), label='omit from log')
#		self.AddItem(self.omit_log)
#		self.omit_out = wx.CheckBox(self, validator=XmlGenAttr('omit_from_output'), label='omit from output')
#		self.AddItem(self.omit_out)

#class MuAliasDetailPanel(MuDetailPanel):

###	attrs = dict(menu=bool, omit_from_history=bool,
###				 expand_variables=bool, echo_alias=bool)
###
###	def Load(self, elem):
###		MuDetailPanel.Load(self, elem)
###		self.add_menu.Value = self.getxmlval('menu')
###		self.omit_hist.Value = self.getxmlval('omit_from_history')
###		self.expand_vars.Value = self.getxmlval('expand_variables')
###		self.echo_alias.Value = self.getxmlval('echo_alias')
###
###	def Save(self):
###		MuDetailPanel.Save(self)
###		self.setxmlval('menu', self.add_menu.Value)
###		self.setxmlval('omit_from_history', self.omit_hist.Value)
###		self.setxmlval('expand_variables', self.expand_vars.Value)
###		self.setxmlval('echo_alias', self.echo_alias.Value)

#	def Create(self):
#		self.CreateGeneral()
#		# input box
#		self.CreateInput()
#		self.add_menu = wx.CheckBox(self, validator=XmlGenAttr('menu'), label='add to menu')
#		self.AddItem(self.add_menu)
#		# output box
#		self.CreateOutput()
#		self.omit_hist = wx.CheckBox(self, validator=XmlGenAttr('omit_from_history'), label='omit from history')
#		self.AddItem(self.omit_hist)
#		self.expand_vars = wx.CheckBox(self, validator=XmlGenAttr('expand_variables'), label='expand variables')
#		self.AddItem(self.expand_vars)
#		self.echo_alias = wx.CheckBox(self, validator=XmlGenAttr('echo_alias'), label='echo alias')
#		self.AddItem(self.echo_alias)

#class MuTriggerDetailPanel(MuDetailPanel):

###	_attrs_ = [('repeat', bool), ('multi_line', bool), ('lines_to_match', int),
###			   (('match_text_colour', bool), ('text_colour', MATCHCOL_CHOICES)),
###			   (
###	attrs = dict(repeat=bool, multi_line=bool, lines_to_match=int,
###				 match_text_colour=bool, text_colour=MATCHCOL_CHOICES,
###				 match_back_colour=bool, back_colour=MATCHCOL_CHOICES,
###				 match_bold=bool, bold=bool, match_italic=bool, italic=bool,
###				 match_inverse=bool, inverse=bool, expand_variables=bool,
###				 lowercase_wildcard=bool, custom_colour=CUSTCOL_CHOICES,
###				 colour_change_type=WHATCOL_CHOICES, other_text_colour=str,
###				 other_back_colour=str, make_bold=bool, make_italic=bool,
###				 make_underline=bool, sound=str, sound_if_inactive=bool,
###				 clipboard_arg=WILDCARD_CHOICES)
###
###	def Load(self, elem):
###		MuDetailPanel.Load(self, elem)
###		self.repeat.Value = self.getxmlval('repeat')
###		self.multi_line.Value = self.getxmlval('multi_line')
###		self.match_lines.Value = self.getxmlval('lines_to_match')
###		self.text_color.Selection = self.getxmlval('match_text_colour') and self.getxmlval('text_colour')
###		self.back_color.Selection = self.getxmlval('match_back_colour') and self.getxmlval('back_colour')
###		self.match_bold.ThreeStateValue = self.get3wayval('match_bold', 'bold')
###		self.match_ital.ThreeStateValue = self.get3wayval('match_italic', 'italic')
###		self.match_invr.ThreeStateValue = self.get3wayval('match_inverse', 'inverse')
###		self.expand_vars.Value = self.getxmlval('expand_variables')
###		self.lower_wilds.Value = self.getxmlval('lowercase_wildcard')
###		self.cust_color.Selection = self.getxmlval('custom_colour')
###		self.what_color.Selection = self.getxmlval('colour_change_type')
###		# other_textcol, other_backcol = self.getxmlval('other_text_colour')
###		self.make_bold.Value = self.getxmlval('make_bold')
###		self.make_ital.Value = self.getxmlval('make_italic')
###		self.make_uline.Value = self.getxmlval('make_underline')
###		self.play_sound.Value = self.getxmlval('sound')
###		self.only_inact.Value = self.getxmlval('sound_if_inactive')
###		self.copy_wild.Selection = self.getxmlval('clipboard_arg')
###
###	def Save(self):
###		MuDetailPanel.Save(self)
###		self.setxmlval('repeat', self.repeat.Value)
###		self.setxmlval('multi_line', self.multi_line.Value)
###		self.setxmlval('lines_to_match', self.match_lines.Value)
###		self.setxmlval('match_text_colour', self.text_color.Selection != 0)
###		self.setxmlval('text_colour', self.text_color.Selection)
###		self.setxmlval('match_back_colour', self.back_color.Selection != 0)
###		self.setxmlval('back_colour', self.back_color.Selection)
###		self.set3wayval('match_bold', 'bold', self.match_bold.ThreeStateValue) # != wx.CHK_UNDETERMINED)
####		self.setxmlval(self.match_bold.ThreeStateValue == wx.CHK_CHECKED)
###		self.set3wayval('match_italic', 'italic', self.match_ital.ThreeStateValue) # != wx.CHK_UNDETERMINED)
####		self.setxmlval('italic', self.match_ital.ThreeStateValue == wx.CHK_CHECKED)
###		self.set3wayval('match_inverse', 'inverse', self.match_invr.ThreeStateValue) # != wx.CHK_UNDETERMINED)
####		self.setxmlval('inverse', self.match_invr.ThreeStateValue == wx.CHK_CHECKED)
###		self.setxmlval('expand_variables', self.expand_vars.Value)
###		self.setxmlval('lowercase_wildcard', self.lower_wilds.Value)
###		self.setxmlval('custom_colour', self.cust_color.Selection)
###		self.setxmlval('colour_change_type', self.what_color.Selection)
###		self.setxmlval('make_bold', self.make_bold.Value)
###		self.setxmlval('make_italic', self.make_ital.Value)
###		self.setxmlval('make_underline', self.make_uline.Value)
###		self.setxmlval('sound', self.play_sound.Value)
###		self.setxmlval('sound_if_inactive', self.only_inact.Value)
###		self.setxmlval('clipboard_arg', self.copy_wild.Selection)

#	def Create(self):
#		self.CreateGeneral()
#		# input box
#		self.CreateInput()
#		self.repeat = wx.CheckBox(self, validator=XmlGenAttr('repeat'), label='repeat on line')
#		self.repeat.Enabled = False
#		self.AddItem(self.repeat)
#		self.AddItem(wx.BoxSizer(wx.HORIZONTAL), slide=True)
#		self.multi_line = wx.CheckBox(self, validator=XmlGenAttr('multi_line'), label='multi-line:')
#		self.multi_line.Enabled = False
#		self.AddItem(self.multi_line)
#		self.Bind(wx.EVT_CHECKBOX, self.OnCheckBox)
##		self.Bind(wx.EVT_CHECKBOX, self.OnRegExpCheck, self.regexp)
#		self.match_lines = wx.SpinCtrl(self, #validator=XmlGenAttr('lines_to_match'),
#									   value='', size=(48,-1), min=2, max=200)
#		self.match_lines.Validator = XmlGenAttr('lines_to_match')
#		self.match_lines.Enabled = False
#		self.AddItem(self.match_lines)
##		hsizer = wx.BoxSizer(wx.HORIZONTAL)
##		hsizer.Add(self.multi_line, 0, wx.ALIGN_CENTER)
##		hsizer.Add(self.match_lines, 0, wx.ALIGN_CENTER)
##		self.AddItem(hsizer, slide=True)
#		# match color row
#		self.AddRow()
#		self.AddItem('Match color:   ')
##		self.AddItem(wx.StaticText(self, label='Match color:  '))
##		self.add_item(wx.StaticText(self, label='text '))
#		self.text_color = wx.Choice(self, validator=XmlListAttr(('match_text_colour', 'text_colour'), MATCHCOL_CHOICES))
##		self.text_color = wx.Choice(self, choices=[x[1] for x in MATCHCOL_CHOICES])
##		self.text_color.MinSize = self.text_color.Size - (EN_WIDTH, 0)
#		self.AddItem(self.text_color)
#		self.AddItem('on  ', space=0)
##		self.AddItem(wx.StaticText(self, label='on  '))
#		self.back_color = wx.Choice(self, validator=XmlListAttr(('match_back_colour', 'back_colour'), MATCHCOL_CHOICES))
##		self.back_color = wx.Choice(self, choices=[x[1] for x in MATCHCOL_CHOICES])
##		self.back_color.Size -= (EN_WIDTH, 0)
#		self.AddItem(self.back_color)
#		self.AddItem('Match style:    ', space=24)
##		self.AddItem(wx.StaticText(self, label='Match style:  '), hspace=24)
#		self.match_bold = wx.CheckBox(self, validator=Xml3stateAttr('match_bold', 'bold'), label='bold') #, style=CHK_3STATE_STYLE)
#		self.AddItem(self.match_bold)
#		self.match_ital = wx.CheckBox(self, validator=Xml3stateAttr('match_italic', 'italic'), label='italic') #, style=CHK_3STATE_STYLE)
#		self.AddItem(self.match_ital)
#		self.match_invr = wx.CheckBox(self, validator=Xml3stateAttr('match_inverse', 'inverse'), label='inverse') #, style=CHK_3STATE_STYLE)
#		self.AddItem(self.match_invr)
#		# output box
#		self.CreateOutput()
#		self.expand_vars = wx.CheckBox(self, validator=XmlGenAttr('expand_variables'), label='expand variables')
#		self.AddItem(self.expand_vars)
#		self.lower_args = wx.CheckBox(self, validator=XmlGenAttr('lowercase_wildcard'), label='lower-case args')
#		self.AddItem(self.lower_args)
#		# change color row
#		self.AddRow()
#		self.AddItem('Change color:   ')
##		self.AddItem(wx.StaticText(self, label='Change color:'))
#		self.cust_color = wx.Choice(self, validator=XmlListAttr('custom_colour', CUSTCOL_CHOICES))
##		self.cust_color = wx.Choice(self, choices=[x[1] for x in CUSTCOL_CHOICES])
#		self.AddItem(self.cust_color)
#		self.what_color = wx.Choice(self, validator=XmlListAttr('colour_change_type', WHATCOL_CHOICES))
##		self.what_color = wx.Choice(self, size=(52,-1), choices=[x[1] for x in WHATCOL_CHOICES])
#		self.AddItem(self.what_color)
###		fg = wx.RadioButton(self, label='text', style=wx.RB_GROUP)
###		self.AddItem(fg)
###		bg = wx.RadioButton(self, label='background')
###		self.AddItem(bg)
###		both = wx.RadioButton(self, label='both')
###		self.AddItem(both)
#		self.AddItem('Change style:    ', space=46)
##		self.AddItem(wx.StaticText(self, label='Change style:  '), 24)
#		self.make_bold = wx.CheckBox(self, validator=XmlGenAttr('make_bold'), label='bold')
#		self.AddItem(self.make_bold)
#		self.make_ital = wx.CheckBox(self, validator=XmlGenAttr('make_italic'), label='italic')
#		self.AddItem(self.make_ital)
#		self.make_uline = wx.CheckBox(self, validator=XmlGenAttr('make_underline'), label='underline')
#		self.AddItem(self.make_uline)
#		# play sound row
#		self.AddRow()
#		self.AddItem('Play sound:  ')
##		self.AddItem(wx.StaticText(self, label='Play sound:'))
#		self.play_sound = wx.FilePickerCtrl(self, validator=XmlGenAttr('sound'))
#		self.play_sound.PickerCtrl.Label = '...'
#		self.play_sound.PickerCtrl.MinSize = (self.play_sound.PickerCtrl.CharWidth*4, -1)
#		self.AddItem(self.play_sound)
#		self.only_inact = wx.CheckBox(self, validator=XmlGenAttr('sound_if_inactive'), label='only if inactive')
#		self.AddItem(self.only_inact)
#		self.AddItem('Copy arg  ', space=16)
##		self.AddItem(wx.StaticText(self, label='Copy wildcard'), 20)
#		self.copy_arg = wx.Choice(self, validator=XmlListAttr('clipboard_arg', COPYARG_CHOICES))
##		self.copy_wild = wx.Choice(self, choices=[x[1] for x in WILDCARD_CHOICES])
#		self.AddItem(self.copy_arg)
#		self.AddItem(wx.StaticText(self, label='to clipboard'))

#	def OnCheckBox(self, event):
#		check = event.IsChecked()
#		ctrl = event.EventObject
#		if ctrl is self.regexp:
#			self.repeat.Enabled = self.multi_line.Enabled = check
#		elif ctrl is self.multi_line:
#			self.match_lines.Enabled = check
#			self.text_color.Enabled = \
#				self.back_color.Enabled = \
#				self.match_bold.Enabled = \
#				self.match_ital.Enabled = \
#				self.match_invr.Enabled = \
#				self.cust_color.Enabled = \
#				self.what_color.Enabled = \
#				self.make_bold.Enabled = \
#				self.make_ital.Enabled = \
#				self.make_uline.Enabled = \
#				self.omit_log.Enabled = \
#				self.omit_out.Enabled = \
#				self.repeat.Enabled = not check


#class MuTimerDetailPanel(MuDetailPanel):
#	pass

#class MuIncludePanel(XmlCtrlPanel):
#	pass

#class MuScriptPanel(XmlCtrlPanel):
#	pass

#class MuCommentPanel(XmlCtrlPanel):
#	pass

#MuPanelType = {'plugin':	MuPluginPanel,
#			   'include':	MuIncludePanel,
#			   'aliases':	MuAliasesGroupPanel,
#			   'alias':		MuAliasDetailPanel,
#			   'triggers':	MuTriggersGroupPanel,
#			   'trigger':	MuTriggerDetailPanel,
#			   'timers':	MuTimersGroupPanel,
#			   'timer':		MuTimerDetailPanel,
#			   'variables':	MuVariablesPanel,
#			   'script':	MuScriptPanel,
#			   etree.Comment: MuCommentPanel}



#class MuDocument:
#	def __init__(self, parent):
#		self.guitree = wx.TreeCtrl(parent)
#		self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, self.guitree)

#	def Load(self, xmltree):
#		assert xmltree.docinfo.root_name == 'muclient'
#		xmlroot = xmltree.getroot()
#		guitree = self.guitree
#		guitree.DeleteAllItems()
#		guiroot = self.guitree.AddRoot(xmlroot.tag, data=xmlroot)
#		for elem in xmlroot:
#			if elem.tag in ('plugin', 'include', 'aliases', 'triggers', 'timers', 'variables', 'script'):
#				title = elem.tag
#			elif elem.tag is etree.Comment:
#				title = (elem.text and elem.text.splitlines()[0].trim()[:20]) or '<comment>'
#			else:
#				continue
#			item = self.guitree.AppendItem(guiroot, title, data=elem)
#			subtag = {'aliases':'alias', 'triggers':'trigger', 'timers':'timer'}.get(elem.tag)
#			for subelem in elem.iterchildren(subtag) if subtag else ():
#				self.guitree.AppendItem(item, subtag, data=subelem)

#	def OnSelChanged(self, event):
#		elem = self.guitree.GetItemPyData(event.Item)
#		panel = self.panels.setdefault(elem.tag, MuPanelType[elem.tag](self))
#		panel.Load(elem)

#class MyFrame(wx.Frame):

#	def __init__(self, parent, id=-1, title='Mushclient Plugin Editor',
#				 pos=wx.DefaultPosition, size=(800, 600),
#				 style=wx.DEFAULT_FRAME_STYLE):
#		wx.Frame.__init__(self, parent, id, title, pos, size, style)

#		self._mgr = wx.aui.AuiManager(self)

#		# create several text controls
#		tree1 = wx.TreeCtrl(self, -1, wx.DefaultPosition, wx.DefaultSize)
#		root = tree1.AddRoot("The Root Item")
#		for x in range(15):
#			child = tree1.AppendItem(root, "Item %d" % x)
##        text1 = wx.TextCtrl(self, -1, 'Pane 1 - sample text',
##                            wx.DefaultPosition, wx.Size(200,150),
##                            wx.NO_BORDER | wx.TE_MULTILINE)

#		panel1 = MuAliasDetailPanel(self)
#		panel1.Create()
#		panel2 = MuTriggerDetailPanel(self)
#		panel2.Create()
#		et = etree.parse(r'C:\local\MUSHclient\MUSHclient_1431\worlds\Aardwolf.mcl')
#		panel2.xmlelem = et.find('triggers/trigger')

###		text2 = wx.TextCtrl(self, -1, 'Pane 2 - sample text',
###							wx.DefaultPosition, wx.Size(200,150),
###							wx.NO_BORDER | wx.TE_MULTILINE)

###		text3 = wx.TextCtrl(self, -1, 'Main content window',
###							wx.DefaultPosition, wx.Size(200,150),
###							wx.NO_BORDER | wx.TE_MULTILINE)

#		# add the panes to the manager
#		self._mgr.AddPane(tree1, wx.LEFT, 'Pane Number One')
#		self._mgr.AddPane(panel2, wx.BOTTOM, 'Pane Number Two')
#		self._mgr.AddPane(panel1, wx.CENTER)

#		# tell the manager to 'commit' all the changes just made
#		self._mgr.Update()

#		self.Bind(wx.EVT_CLOSE, self.OnClose)


#	def OnClose(self, event):
#		# deinitialize the frame manager
#		self._mgr.UnInit()
#		# delete the frame
#		self.Destroy()

##>>> from LuaLexer import LuaLexer
##>>> from LuaParser import LuaParser
##>>> stream=antlr3.FileStream('test.lua')
##>>> lexer=LuaLexer(stream)
##>>> tokens=antlr3.CommonTokenStream(lexer)
##>>> parser=LuaParser(tokens)
##>>> res=parser.block()
##>>> parser.fndefns

app = MuApp()
app.MainLoop()
